package io.bdmc;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import io.bdmc.common.exception.CMSException;
import io.bdmc.common.utils.Constant;
import io.bdmc.modules.bss.entity.DeviceMeasure;
import io.bdmc.modules.bss.entity.DevicePropertyOid;
import io.bdmc.modules.bss.entity.DeviceStatusStatic;
import io.bdmc.modules.bss.service.IDeviceAlarmTypeService;
import io.bdmc.modules.bss.service.IDeviceMeasureService;
import io.bdmc.modules.bss.service.IDevicePropertyOidService;
import io.bdmc.modules.bss.service.IDeviceStatusStaticService;
import io.bdmc.core.snmp.SnmpDataCache;
import io.bdmc.core.snmp.SnmpTrapThreadPool;
import io.bdmc.core.snmp.cache.ConcurrentHashMapCacheUtils;

@Component
public class CmsStartupRunner implements CommandLineRunner {

    @Autowired
    SnmpTrapThreadPool _snmpThreadPool;

    @Autowired
    IDeviceAlarmTypeService _alarmTypeSvs;

    @Autowired
    IDeviceMeasureService _measureSvs;

    @Autowired
    IDevicePropertyOidService _devPropertyOidSvs;

    @Autowired
    IDeviceStatusStaticService _statusStaticSvs;


    @Override
    public void run(String... args) throws CMSException {

        // 查询正在自动测试的任务
        Wrapper<DeviceMeasure> w1 = new QueryWrapper<DeviceMeasure>().eq("action", "1").eq("measure_status", 1);
        List<DeviceMeasure> existAuto = _measureSvs.list(w1);
        for (DeviceMeasure deviceMeasure : existAuto) {
            String key = Constant.MeasureNowMapPrefix + ":" + deviceMeasure.getDeviceIp() + ":"
                    + deviceMeasure.getAction() + ":" + deviceMeasure.getChannel();
            ConcurrentHashMapCacheUtils.setCache(key, deviceMeasure);
        }
        // 加载PropertyOid到内存
        List<DevicePropertyOid> devicePropertyOid = _devPropertyOidSvs.list();
        for (DevicePropertyOid item : devicePropertyOid) {
            SnmpDataCache.putOid2PropertyToMap(item.getOid(), item.getPropertyName());
            SnmpDataCache.putProperty2oidToMap(item.getPropertyName(), item.getOid());
        }
        // System.out.println(">>>>>>>>>>>>>>>加载完成，devicePropertyOidHashMap长度：" +
        // devicePropertyOidHashMap.size() + "<<<<<<<<<<<<<");
        // 加载报警类型到内存
        SnmpDataCache.setAlarmTypeList(_alarmTypeSvs.list());
        // System.out.println(">>>>>>>>>>>>>>>alarmTypeList 加载完成<<<<<<<<<<<<<");

        // 加载静态数据到内存
        for (DeviceStatusStatic dss : _statusStaticSvs.list()) {
            ConcurrentHashMapCacheUtils.setCache(Constant.DeviceStatusStaticPrefix + dss.getDevIpAddr(), dss);
        }

        System.out.println("启动消费者线程");
        _snmpThreadPool.customerSnmpData();
        System.out.println("启动udp监听线程");
        _snmpThreadPool.startUpUdp();

    }
}